package edu.nctu.csie.jichang.database.parser;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import edu.nctu.csie.jichang.database.model.Converter;
import edu.nctu.csie.jichang.database.model.cell.ColumnInfo;
import edu.nctu.csie.jichang.database.model.cell.DBRow;
import edu.nctu.csie.jichang.database.model.cell.DBTable;
import edu.nctu.csie.jichang.database.model.cell.DBTableHeader;
import edu.nctu.csie.jichang.database.model.connection.IDBConnection;
import edu.nctu.csie.jichang.database.util.DBException;


public class ParseDML extends ParseDDL{
	
	/**
	 * get Table
	 * @param pName Table Name
	 * @param pConn Connection
	 * @return DBTable
	 */
	protected DBTable getTable(String pName, IDBConnection pConn) {
		DBTable tTable = new DBTable(pName);
		tTable.addTableHeader(getDBTableHeader(pName,pConn));
		Statement tStat = pConn.getStatement();
		ResultSet tRs   = pConn.getTableData(tStat,pName);
		try {
			while(tRs.next()){
				tTable.addRow(getRow(tRs));
			}
			tRs.close();
			tStat.close();
		} catch (Exception e) {
			throw new DBException(e);
		}
		return tTable;
	}

	public DBTableHeader getDBTableHeader(String pName,IDBConnection pConn) {
		DBTableHeader tHeader = new DBTableHeader();
		for (ColumnInfo c : pConn.getColumnInfo(pName)) {
			tHeader.addTableHead(c);
		}
		return tHeader;
	}
	
	public DBRow getRow(ResultSet pRs) {
		DBRow tRow = new DBRow();
		try {
			ResultSetMetaData tMetaData = pRs.getMetaData();
			for(int i = 1;i<=tMetaData.getColumnCount();i++ ){
				tRow.addCell(tMetaData.getColumnName(i).intern(), Converter.getDataType(tMetaData.getColumnType(i),pRs.getObject(i)) );
			}
		} catch (Exception e) {
			throw new DBException(e);
		}
		return tRow;
	}
}
